/**
 * JAVACC DEMO 1.0
 * @copy right iussoft company All rights reserved.
 * @Package com.iussoft.portal.tags
 */
package com.apache.portal.tags;

import java.io.UnsupportedEncodingException;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;

import com.apache.tools.StrUtil;

/**
 * description:  字符串截取标签
 * @author Hou Dayu 创建时间：2016-8-26
 */
@SuppressWarnings("serial")
public class PortalSubStringTag extends TagSupport {

	private String str;
	private int length;
	private String defStr = "...";

	//private JspWriter writer;

	public int doStartTag() throws JspException {
		try {
			if (StrUtil.isNotNull(str)) {
				JspWriter writer = this.pageContext.getOut();// 返回一个JspWriter
				writer.print(getTitleToTen());
				writer.flush();
			}
		} catch (Exception e) {
			return super.SKIP_BODY;
		}
		return super.EVAL_BODY_INCLUDE;
	}

	private String getTitleToTen() throws Exception {
		int textLength = str.length();
		int byteLength = 0;
		StringBuffer returnStr = new StringBuffer();
		for (int i = 0; i < textLength && byteLength < length * 2; i++) {
			String str_i = str.substring(i, i + 1);
			if (str_i.getBytes().length == 1) {//英文  
				byteLength++;
			} else {//中文  
				byteLength += 3;
			}
			returnStr.append(str_i);
		}
		try {
			if (byteLength < str.getBytes("UTF-8").length) {//getBytes("GBK")每个汉字长2，getBytes("UTF-8")每个汉字长度为3  
				returnStr.append(defStr);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return returnStr.toString();
	}

	//	public int doEndTag() {
	//		try {
	//			if (null != writer)
	//				writer.close();
	//		} catch (Exception e) {
	//		}
	//		return super.EVAL_BODY_INCLUDE;
	//	}

	public String getStr() {
		return str;
	}

	public void setStr(String str) {
		this.str = str;
	}

	public int getLength() {
		return length;
	}

	public void setLength(int length) {
		this.length = length;
	}

	public String getDefStr() {
		return defStr;
	}

	public void setDefStr(String defStr) {
		this.defStr = defStr;
	}

}
